{% extends "base.html" %}

{% block title %}公共参数{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-cogs me-2"></i>公共参数</h2>
                <button type="button" class="btn btn-primary" onclick="showAddParameterModal()">
                    <i class="fas fa-plus me-1"></i>新增参数
                </button>
            </div>

            <!-- 使用说明 -->
            <div class="alert alert-info mb-4">
                <h5><i class="fas fa-info-circle me-2"></i>使用说明</h5>
                <p class="mb-2">公共参数可以在您的脚本中直接使用，系统会自动将参数注入到脚本执行环境中：</p>
                <ul class="mb-2">
                    <li><strong>Python脚本：</strong>通过环境变量访问，例如：<code>import os; value = os.environ.get('PARAM_NAME')</code></li>
                    <li><strong>参数命名：</strong>系统会自动在参数名前添加 <code>GLOBAL_</code> 前缀，避免与系统变量冲突</li>
                </ul>
                <p class="mb-0"><strong>注意：</strong>公共参数仅对当前用户的任务有效，不同用户之间的参数相互隔离。</p>
            </div>

            <!-- 参数列表 -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>参数名称</th>
                                    <th>参数值</th>
                                    <th>描述</th>
                                    <th>加密</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="parameterTableBody">
                                <!-- 参数列表将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新增/编辑参数模态框 -->
<div class="modal fade" id="parameterModal" tabindex="-1" aria-labelledby="parameterModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="parameterModalLabel">新增公共参数</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="parameterForm">
                    <input type="hidden" id="parameterId" name="id">
                    
                    <div class="mb-3">
                        <label for="parameterName" class="form-label">参数名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="parameterName" name="name" required pattern="[A-Za-z_][A-Za-z0-9_]*">
                        <div class="form-text">
                            参数名称只能包含字母、数字和下划线，且必须以字母或下划线开头<br>
                            系统会自动添加 <code>GLOBAL_</code> 前缀，实际环境变量名为：<code>GLOBAL_参数名称</code>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="parameterValue" class="form-label">参数值 <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="parameterValue" name="value" rows="3" required></textarea>
                        <div class="form-text">参数的具体值，支持多行文本</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="parameterDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="parameterDescription" name="description" rows="2"></textarea>
                        <div class="form-text">可选，描述这个参数的用途和含义</div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="isEncrypted" name="is_encrypted">
                            <label class="form-check-label" for="isEncrypted">
                                加密存储
                            </label>
                            <div class="form-text">
                                启用后，参数值将加密存储，适用于密码、密钥等敏感信息<br>
                                <strong>注意：</strong>加密参数在界面上不会显示真实值
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="isEnabled" name="is_enabled" checked>
                            <label class="form-check-label" for="isEnabled">
                                启用此参数
                            </label>
                            <div class="form-text">禁用的参数不会注入到脚本执行环境中</div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveParameter()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除参数 "<span id="deleteParameterName"></span>" 吗？</p>
                <p class="text-danger mb-0">此操作不可恢复，删除后所有使用此参数的脚本可能会受到影响。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">确认删除</button>
            </div>
        </div>
    </div>
</div>

<script>
let currentParameterId = null;
let deleteParameterId = null;

// 页面加载完成后初始化
$(document).ready(function() {
    loadParameters();
});

// 加载参数列表
function loadParameters() {
    $.ajax({
        url: '/api/global-parameters',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                renderParameterTable(response.data);
            } else {
                showAlert('加载参数列表失败：' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('加载参数列表失败，请检查网络连接', 'danger');
        }
    });
}

// 渲染参数表格
function renderParameterTable(parameters) {
    const tbody = document.getElementById('parameterTableBody');
    
    if (parameters.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">暂无公共参数</td></tr>';
        return;
    }
    
    tbody.innerHTML = parameters.map(param => `
        <tr>
            <td>
                <code>GLOBAL_${param.name}</code>
                <br><small class="text-muted">${param.name}</small>
            </td>
            <td>
                <span class="text-truncate d-inline-block" style="max-width: 200px;" title="${param.value}">
                    ${param.is_encrypted ? '***' : param.value}
                </span>
            </td>
            <td>
                <span class="text-truncate d-inline-block" style="max-width: 150px;" title="${param.description || ''}">
                    ${param.description || '-'}
                </span>
            </td>
            <td>
                ${param.is_encrypted ? '<i class="fas fa-lock text-warning" title="已加密"></i>' : '<i class="fas fa-unlock text-muted" title="未加密"></i>'}
            </td>
            <td>
                <span class="badge ${param.is_enabled ? 'bg-success' : 'bg-secondary'}">
                    ${param.is_enabled ? '启用' : '禁用'}
                </span>
            </td>
            <td>
                <small class="text-muted">${formatDateTime(param.created_at)}</small>
            </td>
            <td>
                <button class="btn btn-sm btn-outline-primary me-1" onclick="editParameter(${param.id})" title="编辑">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="showDeleteModal(${param.id}, '${param.name}')" title="删除">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

// 显示新增参数模态框
function showAddParameterModal() {
    currentParameterId = null;
    document.getElementById('parameterModalLabel').textContent = '新增公共参数';
    document.getElementById('parameterForm').reset();
    document.getElementById('parameterId').value = '';
    new bootstrap.Modal(document.getElementById('parameterModal')).show();
}

// 编辑参数
function editParameter(id) {
    currentParameterId = id;
    
    $.ajax({
        url: `/api/global-parameters/${id}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const param = response.data;
                document.getElementById('parameterModalLabel').textContent = '编辑公共参数';
                document.getElementById('parameterId').value = param.id;
                document.getElementById('parameterName').value = param.name;
                document.getElementById('parameterValue').value = param.is_encrypted ? '' : param.value;
                document.getElementById('parameterDescription').value = param.description || '';
                document.getElementById('isEncrypted').checked = param.is_encrypted;
                document.getElementById('isEnabled').checked = param.is_enabled;
                
                // 如果是加密参数，显示提示
                if (param.is_encrypted) {
                    document.getElementById('parameterValue').placeholder = '留空表示不修改加密值';
                }
                
                new bootstrap.Modal(document.getElementById('parameterModal')).show();
            } else {
                showAlert('获取参数信息失败：' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('获取参数信息失败，请检查网络连接', 'danger');
        }
    });
}

// 保存参数
function saveParameter() {
    const form = document.getElementById('parameterForm');
    const formData = new FormData(form);
    
    // 验证参数名称格式
    const name = formData.get('name');
    if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
        showAlert('参数名称格式不正确，只能包含字母、数字和下划线，且必须以字母或下划线开头', 'danger');
        return;
    }
    
    const data = {
        name: formData.get('name'),
        value: formData.get('value'),
        description: formData.get('description'),
        is_encrypted: formData.get('is_encrypted') === 'on',
        is_enabled: formData.get('is_enabled') === 'on'
    };
    
    const url = currentParameterId ? `/api/global-parameters/${currentParameterId}` : '/api/global-parameters';
    const method = currentParameterId ? 'PUT' : 'POST';
    
    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function(response) {
            if (response.success) {
                showAlert(currentParameterId ? '参数更新成功' : '参数创建成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('parameterModal')).hide();
                loadParameters();
            } else {
                showAlert('保存失败：' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('保存失败，请检查网络连接', 'danger');
        }
    });
}

// 显示删除确认模态框
function showDeleteModal(id, name) {
    deleteParameterId = id;
    document.getElementById('deleteParameterName').textContent = name;
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}

// 确认删除
function confirmDelete() {
    if (!deleteParameterId) return;
    
    $.ajax({
        url: `/api/global-parameters/${deleteParameterId}`,
        method: 'DELETE',
        success: function(response) {
            if (response.success) {
                showAlert('参数删除成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                loadParameters();
            } else {
                showAlert('删除失败：' + response.message, 'danger');
            }
        },
        error: function() {
            showAlert('删除失败，请检查网络连接', 'danger');
        }
    });
}

// 格式化日期时间
function formatDateTime(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// 显示提示消息
function showAlert(message, type) {
    // 使用基础模板中定义的全局showMessage函数（即showToast）
    
    // 映射类型到Toast支持的类型
    let toastType = type;
    
    if (type === 'danger') {
        toastType = 'error';
    } else if (type === 'warning') {
        toastType = 'warning';
    } else if (type === 'success') {
        toastType = 'success';
    } else {
        toastType = 'info';
    }
    
    showMessage(message, toastType, 3000);
}
</script>
{% endblock %}